#pragma once
#include "widgets.h"
#include <QJsonArray>
#include <QJsonObject>
#include <QFrame>
#include <functional>

#define ITEM_DEFAULT_HEIGHT 25

class QAbstractItemDelegate;
class IKeySearchEngine
{
public:
	virtual void search(int serialNum, const QString& key) = 0;
	virtual void setResultCallback(std::function<void(int, QJsonArray)> fun) = 0;
	virtual void onResultSelected(const QString& key) = 0;
};

class KeySearchEdit;
class KeySearchResultDlg;
class DefaultItemDelegate;
class S_WIDGETS_EXPORT KeySearchWidget : public QFrame
{
Q_OBJECT
public:
	KeySearchWidget(QWidget* parent);

	void setSearchText(const QString& txt);
	void appendSearchText(const QString& txt);
	void setPromptText(const QString& txt);
	void setResultItemDelegate(QAbstractItemDelegate* itemDelegate);
	void setResultDlgMaxHeight(int h);
	void setResultDlgWidth(int w);
	void setColumnsWidth(int count, ...);
	void setSearchWhenEmpty(bool v);
	void setSearchEngine(IKeySearchEngine* se);
	IKeySearchEngine* searchEngine() { return m_searchEngine; }
	void foucsChanged(bool v);
	void hideResult();
	void clearEditFocus();

signals:
	void itemClicked(QJsonValue obj);
	void resultReached(QJsonArray results);
	void resultHide();
	void searchFocusChanged(bool v);

protected slots:
	void onSearchTextChanged(const QString& searchKey);
	void onResultReach(int, QJsonArray results);

protected:

private:
	KeySearchEdit* m_edit = nullptr;
	KeySearchResultDlg* m_resultDlg = nullptr;
	IKeySearchEngine* m_searchEngine = nullptr;
	DefaultItemDelegate* m_delegate = nullptr;
	bool	m_searchWhenEmpty = false;
	uint32_t		m_searchSerialNum = 0;
	QString		m_promptText;
};